//
//  OneViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 15/11/16.
//  Copyright © 2015年 sgone. All rights reserved.
//

#import "OneViewController.h"
#import "OneDetailViewController.h"
#import "AFNetworking.h"
#import "Common.h"
#import "DataSingleton.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "MBProgressHUD+MJ.h"
#import "LoginViewController.h"

@interface OneViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
//获取网络信息的数组
@property(nonatomic,strong) NSMutableArray *list;
//网路请求
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) DataSingleton *dataSingleton;

//无订单显示图片view加image以及button
@property(nonatomic,strong) UIView *view20w;
@property(nonatomic,strong) UIButton *btnw;
@property(nonatomic,strong) UIImageView *imageVieww;


@property(nonatomic,strong) NSString *download_url;



@end

@implementation OneViewController


static int cur_page = 1;


//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}


//解除通知
-(void)dealloc
{

    [[NSNotificationCenter defaultCenter]removeObserver:self];


}


-(void)viewWillAppear:(BOOL)animated

{

}


#pragma mrak 获取版本号
-(void)banbenAPI
{

    NSString *str = [NSString stringWithFormat:@"%@get_version",SERVER_ADDRESS];
    NSDictionary *parmas = @{@"device_type" : @"1"};
    [self.manager POST:str parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
//        NSLog(@"1111111%@  %@",responseObject[@"data"][@"version_name"],responseObject[@"data"]);
 
        if ([responseObject[@"error_flag"] intValue] == 0)
        {
            
            
            NSString *lasteVersion2 = [[responseObject objectForKey:@"data"]objectForKey:@"version_name"];
            
            
            //获取此应用的版本号
            NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
            NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];//1.0.0
//            NSLog(@"89898989 %@    %@",lasteVersion2,currentVersion);
            
            
            
            //产生下载链接地址
            self.download_url = [NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"] objectForKey:@"download_url"]];
            
            
            
            
            //两个点的，最后那个是无效的
            
            //  NSString *trackName  = lasteVersion2;
            if (![currentVersion isEqualToString:lasteVersion2] ) {
                NSString *titleStr = [NSString stringWithFormat:@"发现新版本: %@,是否升级?",lasteVersion2];
                
                
                UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:titleStr delegate:self cancelButtonTitle:@"稍后再说" otherButtonTitles:@"立即升级", nil];
                alter.tag = 200;
                [alter show];}
            

        
        
        }
        else
        {
        
        
//            NSLog(@"错误提示  %@",responseObject[@"result_msg"]);
        
        }
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
       
        
        
    }];



}



#pragma mark -alterView代理的实现
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
//    NSLog(@"下载链接地址 %@",self.download_url);
    if (alertView.tag == 200 ) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.download_url]];
            
        }
    }
    
    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    self.list = [NSMutableArray arrayWithCapacity:0];

    self.tableView.backgroundColor = BACKGROUND2;
    
    
    self.dataSingleton = [DataSingleton sharedDataSingleton];
   //通知这个页面进行刷新
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setupRefresh) name:@"fahuo" object:nil];
    
    
  

    
    self.view20w = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-48-64-46)];

    
    self.view20w.backgroundColor= BACKGROUND2;
    [self.view addSubview:self.view20w];

    
    self.imageVieww = [[UIImageView alloc]initWithFrame:CGRectMake((self.view20w.frame.size.width-60)/2, (self.view20w.frame.size.height-80-70)/2, 60, 80)];
    self.imageVieww.image = [UIImage imageNamed:@"order_null"];
    
    [self.view20w addSubview:self.imageVieww];
    
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0,(self.view20w.frame.size.height-80-70)/2+self.imageVieww.frame.size.height+10, self.view20w.frame.size.width, 40)];
    lbl.text = @"  还没有新的订单哦~";
    lbl.textColor = [UIColor grayColor];
    lbl.textAlignment  = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:18];
    [self.view20w addSubview:lbl];
    
    self.btnw  = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-48-64-46)];
    [self.btnw addTarget:self action:@selector(headerRereshing1) forControlEvents:UIControlEventTouchUpInside];
    [self.view20w addSubview:self.btnw];
    self.view20w.hidden = YES;
    self.tableView.hidden = NO;
    
    
  

    
    
    //进行刷新控制
    [self setupRefresh];
    
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //异步加载数据
        //进入判断版本号,有更新提示用户更新
    
        [self banbenAPI];
        
    });
    
    

    
    
//    self.btnw = [[UIButton alloc]initWithFrame:CGRectMake(0,(self.view20w.frame.size.height -80)/2+self.imageVieww.frame.size.height+10, self.view20w.frame.size.width, 40)];
//    [self.btnw setTitle:@"  您还没有新的订单哦~" forState:UIControlStateNormal];
//    [self.btnw setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//    self.btnw.titleLabel.font = [UIFont systemFontOfSize:17];
//    [self.view20w addSubview:self.btnw];
    
    
    
    
    
    
    

    
}








#pragma mark刷新数据
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing1)];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing1)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"正在帮你加载中";
    
    
    
    
}


- (void)headerRereshing1
{
    [self.list removeAllObjects];
    cur_page = 1;
   
    //加载数据
    [self sendAPI];
    

}


- (void)footerRereshing1
{
    
      cur_page++;
        [self sendAPI2];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];

}




-(void)sendAPI
{


    NSString *urlStr = [NSString stringWithFormat:@"%@order_list",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataSingleton.phone , @"uToken" : self.dataSingleton.uToken , @"status" : @"7" , @"cur_page" : @"1"};
    
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
     
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
        
        if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
            
            [self.tableView headerEndRefreshing];
 
            return ;
        }
        else
        {
//            NSLog(@"uiuiuu ");
            NSArray *array = responseObject[@"data"][@"list"];
            if (array.count != 0 )
            {
          
             

                
                self.list = [NSMutableArray arrayWithArray:array];
    
                self.view20w.hidden = YES;
   
            }
            else
            {
                self.view20w.hidden = NO;
                self.tableView.hidden = YES;
            
            }
            
            
            
//            NSLog(@"9809899090  %@",self.list);
        }
           

            [self.tableView reloadData];
            [self.tableView headerEndRefreshing];
            
        }
        
        else
            
        {
        
            [self.tableView headerEndRefreshing];
            
            self.view20w.hidden = NO;
            self.tableView.hidden = YES;
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataSingleton removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
                
            }

        
        
        
        
        }
        
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [self.tableView headerEndRefreshing];
        self.view20w.hidden = NO;
        self.tableView.hidden= YES;

        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];

        
        
    }];
}




#pragma mark 进行footer的加载数据
-(void)sendAPI2
{

    

    NSString *urlStr = [NSString stringWithFormat:@"%@order_list",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataSingleton.phone , @"uToken" : self.dataSingleton.uToken , @"status" : @"7" , @"cur_page" : [NSString stringWithFormat:@"%d",cur_page]};
    
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                [self.tableView footerEndRefreshing];
                
                return ;
            }
            else
            {
                NSArray *array = responseObject[@"data"][@"list"];

                
                if (array.count != 0)
                {
                    [self.list removeAllObjects];
                    self.list = [NSMutableArray arrayWithArray:array];

                    
                
                }
//                else
//                {
//                    return;
//                
//                }
                
                
            }
            [self.tableView footerEndRefreshing];
//            NSLog(@"7777  %d",cur_page);

            [self.tableView reloadData];
        }
        else
        {
        
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataSingleton removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
                
            }

        
        
        
        }
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [self.tableView footerEndRefreshing];
        
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
        
        
    }];

    



}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return self.list.count;

}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;


}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{


    return 162;


}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 20;


}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{

    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
    view1.backgroundColor = [UIColor whiteColor];

    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 53, ViewWidth, 0.3)];
    view2.backgroundColor = [UIColor lightGrayColor];
    [view1 addSubview:view2];
    
    
    UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(0, 53+54, ViewWidth, 0.3)];
    view3.backgroundColor = [UIColor lightGrayColor];
    [view1 addSubview:view3];
    
    
    
    UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 54)];
    lbl1.text = @"订单编号";
    lbl1.textColor = [UIColor lightGrayColor];
    [view1 addSubview:lbl1];
    lbl1.font = [UIFont systemFontOfSize:16];
    
    UILabel *lbla = [[UILabel alloc]initWithFrame:CGRectMake(90, 0, 230, 54)];
    lbla.text = [NSString stringWithFormat:@"%@",[self.list[section] objectForKey:@"order_id"]];
    [view1 addSubview:lbla];
    lbla.font = [UIFont systemFontOfSize:15];
    
    
    UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(10, 53, 100, 54)];
    lbl2.text = @"送货地址";
    lbl2.textColor = [UIColor lightGrayColor];
    [view1 addSubview:lbl2];
    lbl2.font = [UIFont systemFontOfSize:16];
    


//    
//    UILabel *lblb = [[UILabel alloc]initWithFrame:CGRectMake(90, 53, ViewWidth *0.72, 54)];
//    [lblb setNumberOfLines:0];
//    
//    lblb.text = [NSString stringWithFormat:@"%@",[self.list[section] objectForKey:@"address"]];
//    CGSize size = CGSizeMake(230, 54);
//    CGSize labelMSSize = [lblb.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
//    [lblb setFrame:CGRectMake(90, 0, labelMSSize.width , labelMSSize.height)];

    
    
    
//    
//    
//    [view1 addSubview:lblb];
//    lblb.font = [UIFont systemFontOfSize:14];

    UILabel *lblb = [[UILabel alloc]initWithFrame:CGRectMake(90, 53, ViewWidth *0.72, 54)];
    
    [lblb setNumberOfLines:0];
    lblb.font = [UIFont systemFontOfSize:14];
    lblb.text = [NSString stringWithFormat:@"%@",[self.list[section] objectForKey:@"address"]];
    CGSize size = CGSizeMake(230, 54);
    CGSize labelMSSize = [lblb.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    [lblb setFrame:CGRectMake(90, 53+10, labelMSSize.width , labelMSSize.height)];
    
    [view1 addSubview:lblb];

    
    
    
    
    UILabel *lbl3 = [[UILabel alloc]initWithFrame:CGRectMake(10, 53 +54, 100, 54)];
    lbl3.text = @"送货时间";
    lbl3.textColor = [UIColor lightGrayColor];
    [view1 addSubview:lbl3];
    lbl3.font = [UIFont systemFontOfSize:16];
    
    
    
    UILabel *lblc = [[UILabel alloc]initWithFrame:CGRectMake(90, 53 + 54, 230, 54)];
    lblc.text = [NSString stringWithFormat:@"%@",[[self.list[section] objectForKey:@"product_list"][0] objectForKey:@"create_time"]];
    [view1 addSubview:lblc];
    lblc.font = [UIFont systemFontOfSize:15];
    
    
    
    
    

    
    
    
   

    
    
    


    return view1;

}




-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell3";
  
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
     
        cell.backgroundColor = TiaoColor;
    }
    
    NSString *shopUrl = [NSString stringWithFormat:@"%@",[self.list[indexPath.section] objectForKey:@"shopUrl"]];
    NSString *shopImage = [NSString stringWithFormat:@"%@",[self.list[indexPath.section] objectForKey:@"shopImage"]];
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@",shopUrl,shopImage];
    NSURL *url = [NSURL URLWithString:imageUrl];
    
    
//    cell.textLabel.text = [NSString stringWithFormat:@"%@",[self.list[indexPath.section] objectForKey:@"shopName"]];
    
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(8, 4, 36, 36)];

    
    [cell addSubview:image];
    
    [image sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"backImage"]];

//    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"backImage"]];
    
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(54, 0, 200, 44)];
    lbl.text = [NSString stringWithFormat:@"%@",[self.list[indexPath.section] objectForKey:@"shopName"]];
    lbl.font = [UIFont systemFontOfSize:16];
    [cell addSubview:lbl];
    
    
    
    

     return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


    if ([self.tableView isHeaderRefreshing]  || [self.tableView isFooterRefreshing])
    {
        return;
    }

    
    NSInteger row = [indexPath section];
    NSDictionary *dict = [self.list objectAtIndex:row];
    OneDetailViewController *oneD = [[OneDetailViewController alloc]initWithNibName:nil bundle:nil];

    oneD.dict = dict;
    oneD.oID = [dict objectForKey:@"order_id"];
    [self.navigationController pushViewController:oneD animated:YES];

}


@end
